﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace wpf_ImageSearch.Model.YahooApis
{
    public class YahooApiClient
    {
        public YahooApiClient(string appid)
        {
            this.appid = appid;
        }

        private string appid;

        public ImageSearchResult ImageSearch(string query, SearchTypes type = SearchTypes.All,
            int results = 10, int start = 1, ImageFormats format = ImageFormats.Any,
            bool adult_ok = false, ImageColorationTypes coloration = ImageColorationTypes.Any,
            string site = null)
        {
            var param = new Dictionary<string, string>();
            param.Add("appid", this.appid);
            param.Add("query", query);
            param.Add("type", type.ToString().ToLower());
            param.Add("results", results.ToString());
            param.Add("start", start.ToString());
            param.Add("format", format.ToString().ToLower());
            if (adult_ok)
                param.Add("adult_ok", "1");
            param.Add("coloration", coloration.ToString().ToLower());
            if (!string.IsNullOrEmpty(site))
                param.Add("site", site);

            var reqUri = "http://search.yahooapis.jp/ImageSearchService/V2/imageSearch?" +
                string.Join("&", param.Select(_ => _.Key + "=" + _.Value));

            using (var wc = new WebClient())
            {
                try
                {
                    wc.Encoding = Encoding.UTF8;
                    return new ImageSearchResult(wc.DownloadString(reqUri));
                }
                catch (WebException ex)
                {
                    using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        return new ImageSearchResult(reader.ReadToEnd());
                    }
                }
            }
        }
    }
}
